package com.legrand.www.module.security.util;

import com.legrand.www.module.security.authentication.UserAuthentication;
import com.legrand.www.module.security.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * @author xiah
 * date 2018/5/5 16:22
 * 获得当前登录用户的信息
 */
public class UserUtil {
    public static Optional getUserContext() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof UserAuthentication) {
            UserAuthentication jwtAuthenticationToken = (UserAuthentication) authentication;
            return Optional.of(jwtAuthenticationToken.getPrincipal());
        }
        return Optional.empty();
    }

    public static String getUserName() {
        User user = (User) getUserContext().get();
        return user.getUserName();
    }

}
